<?php

declare(strict_types=1);

namespace app\index\controller;

use app\common\model\OrderTemporary;
use app\common\model\Refund;
use app\common\tool\Result;
use think\facade\View;
use think\Response;
use think\exception\ValidateException;

class Order extends Base
{
    public function success()
    {
        return View::fetch();
    }

    public function index()
    {
        $temporary = OrderTemporary::getTemporary($this->user->id);
        if ($temporary['code'] != 1) return redirect('/');
        View::assign('temporary', $temporary['data']);
        return View::fetch();
    }

    /**
     * @return Response
     * 原点 2023年1月4日14:47:49 提交订单
     */
    public function submit(): Response
    {
        try {
            $result = OrderTemporary::submit($this->request->post(), $this->user);
            if ($result['code'] != 1) {
                return Result::fail($result['msg']);
            }
            return Result::fastReturn([
                'code' => 1,
                'msg'  => '订单已生成',
                'url'  => url('order/payment')->build() . '?id=' . $result['data']
            ]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @param $id
     * 原点 2023年1月5日08:58:04 获取待支付的订单
     */
    public function payment($id)
    {
        $info = OrderTemporary::getPayment($id);
        if (empty($info['data'])) return redirect(url('user/index')->build());
        View::assign('info', $info['data']['order']);
        return View::fetch();
    }

    /**
     * @return Response
     * 原点 2023年1月5日09:09:48 支付订单
     */
    public function confirmPayment(): Response
    {
        try {
            return Result::fastReturn(OrderTemporary::payment($this->request->post(), $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function my_order()
    {
        return View::fetch();
    }

    /**
     * 申请退款
     */
    public function refund_order()
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Refund');
            return Result::fastReturn(Refund::refund_order($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }
    /**
     * 申请退款详情
     */
    public function refund()
    {
        $param = $this->request->get();
        $info = OrderTemporary::where(['uid' => $this->user->id, 'id' => $param['id']])
            ->withoutField('update_time,is_del')
            ->with(['productsField', 'p', 'c', 'd', 'express'])
            ->find();
        if (empty($info)) return redirect('/');
        $info->statusCode = $info->getData('status');
        $info->friendlyText = getProductOrderFriendly($info->statusCode);
        View::assign('info', $info);
        View::assign('type', $param['type']);
        return View::fetch();
    }
    /**
     * 退款详情
     */
    public function refund_details()
    {
        $param = $this->request->get();
        $info = OrderTemporary::where(['uid' => $this->user->id, 'id' => $param['id']])
            ->withoutField('update_time')
            ->with(['productsField', 'p', 'c', 'd', 'express'])
            ->find();
        if (empty($info)) return redirect('/');
        $info->statusCode = $info->getData('status');
        $refund = Refund::where('order_id', $info->id)->with(['express'])->find();
        $info->refund = $refund;
        $info->friendlyText = getRefundFriendly($refund->status);
        // print('<pre>');print_r($info);die;
        View::assign('info', $info);
        return View::fetch();
    }
    /**
     * 上传物流
     */
    public function refund_express()
    {
        $param = $this->request->get();
        $refund = Refund::where('id', $param['id'])->with(['express'])->find();
        View::assign([
            'express' => \app\common\model\Express::where(['status' => 1])->select(),
            'info' => $refund
        ]);
        return View::fetch();
    }
    /**
     * 上传物流提交
     */
    public function refund_post()
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'RefundExpress');
            $info = Refund::find($param['id']);
            if  ($info->status != 2) {
                throw new \Exception('当前状态不能上传物流信息');
            }
            $info->express_id = $param['express_id'];
            $info->no_number = $param['no_number'];
            $info->status = 3;
            $info->save();
            return Result::fastReturn(['code'=>1,'msg'=>'上传物流成功！','url'=>'/index/order/my_order.html']);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
    }
    public function my_order_details()
    {
        $info = OrderTemporary::where(['uid' => $this->user->id, 'id' => $this->request->get('id')])
            ->withoutField('update_time,is_del')
            ->with(['productsField', 'p', 'c', 'd', 'express'])
            ->find();
        if (empty($info)) return redirect('/');
        $info->statusCode = $info->getData('status');
        $info->friendlyText = getProductOrderFriendly($info->statusCode);
        View::assign('info', $info);
        return View::fetch();
    }



    public function getList(): Response
    {
        try {
            $param = $this->request->get();
            $map = [['uid', '=', $this->user->id]];
            if (isset($param['type']) && $param['type']) {
                $map[] = ['status', '=', $param['type']];
            }

            $list = OrderTemporary::getPageList(
                $map,
                'id,sn,total_amount,real_amount,create_time,status,order_type',
                $this->getPage(),
                $this->getLimit(),
                false,
                ['productsField']
            );

            foreach ($list['data'] as &$v) {
                $v->statusCode = $v->getData('status');
                // $refund = Refund::where(['order_id'=>$v->id,'uid'=>$this->user->id])->find();
                // $v->refund_status = $refund ? ($refund->status == 4 ? 1 : 0) : 0;
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function edit(): Response
    {
        return Result::fastReturn(OrderTemporary::edit($this->request->post(), $this->user));
    }
}
